1099D - Sum in the tree - CodeForces Solution


constructive algorithms trees *1600

Please click on ads to support us..

Python Code:

from __future__ import division, print_function

import threading

threading.stack_size(2**27)
import sys

sys.setrecursionlimit(10**7)


def ain():
    return list(map(int, sin().split()))


def sin():
    return input()


def inin():
    return int(input())


q = 0


def dfs(n, d, v, c, a):
    global q
    if q == -1:
        return
    if a[n - 1] < 0:
        if n not in d:
            return
        x = d[n]
        m = 100000000000
        for i in x:
            if a[i - 1] > -1:
                m = min(m, a[i - 1])
        a[n - 1] = m
    if c > a[n - 1]:
        q = -1
        return
    q += a[n - 1] - c
    v[n] = 1
    if n not in d:
        return
    x = d[n]
    for i in x:
        if i not in v:
            z = a[n - 1]
            _ = dfs(i, d, v, z, a)
    return


def main():
    n = inin()
    a = ain()
    b = ain()
    g = {}
    for i in range(2, n + 1):
        if a[i - 2] in g:
            g[a[i - 2]].append(i)
        else:
            g[a[i - 2]] = [i]
    v = {}
    x = 0
    x = dfs(1, g, v, x, b)
    print(q)


py2 = round(0.5)
if py2:
    from future_builtins import map

    range = xrange
import os
import sys
from io import BytesIO

BUFSIZE = 8192


class FastIO(BytesIO):
    newlines = 0

    def __init__(self, file):
        self._file = file
        self._fd = file.fileno()
        self.writable = "x" in file.mode or "w" in file.mode
        self.write = super(FastIO, self).write if self.writable else None

    def _fill(self):
        s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
        self.seek(
            (self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0]
        )
        return s

    def read(self):
        while self._fill():
            pass
        return super(FastIO, self).read()

    def readline(self):
        while self.newlines == 0:
            s = self._fill()
            self.newlines = s.count(b"\n") + (not s)
        self.newlines -= 1
        return super(FastIO, self).readline()


input = lambda: sys.stdin.readline().rstrip("\r\n")
import sys


class ostream:
    def __lshift__(self, a):
        sys.stdout.write(str(a))
        return self


_ = ostream()
threading.Thread(target=main).start()


Comments

Submit
0 Comments
More Questions

1295. Find Numbers with Even Number of Digits
1704. Determine if String Halves Are Alike
1732. Find the Highest Altitude
709. To Lower Case
1688. Count of Matches in Tournament
1684. Count the Number of Consistent Strings
1588. Sum of All Odd Length Subarrays
1662. Check If Two String Arrays are Equivalent
1832. Check if the Sentence Is Pangram
1678. Goal Parser Interpretation
1389. Create Target Array in the Given Order
1313. Decompress Run-Length Encoded List
1281. Subtract the Product and Sum of Digits of an Integer
1342. Number of Steps to Reduce a Number to Zero
1528. Shuffle String
1365. How Many Numbers Are Smaller Than the Current Number
771. Jewels and Stones
1512. Number of Good Pairs
672. Richest Customer Wealth
1470. Shuffle the Array
1431. Kids With the Greatest Number of Candies
1480. Running Sum of 1d Array
682. Baseball Game
496. Next Greater Element I
232. Implement Queue using Stacks
844. Backspace String Compare
20. Valid Parentheses
746. Min Cost Climbing Stairs
392. Is Subsequence
70. Climbing Stairs